<style lang="less">
// @import "./departmentManage.less";
</style>
<template>
  <div class="search">
    <Card>
      <Row class="operation">
        <Col :span="6">
          <Poptip trigger="click" placement="right-start" title="选择商品分类" style="width:250px">
          <Input v-model="searchForm.className" readonly style="width: 250px" placeholder="请选择分类"/>
            <div slot="content" style="position:relative;min-height:5vh">
              <Tree :data="dataEdit" :load-data="loadEditData" @on-select-change="selectTreeEdit($event, 3)" ref="treeOne"></Tree>
              <Spin size="large" fix v-if="loadingEdit"></Spin>
            </div>
          </Poptip>
        </Col>
        
        <Button @click="clearAll" type="default">清空</Button>
        <Button @click="getParentList" type="primary">搜索</Button>
        <Button @click="add" type="primary" icon="md-add">添加规格属性</Button>
        <Button @click="addRoot" icon="md-add">添加一级规格</Button>
        <Button @click="delAll" icon="md-trash">删除</Button>
        <Button @click="getParentList" icon="md-refresh">刷新</Button>
        <i-switch v-model="strict" size="large" style="margin-left:5px">
          <span slot="open">级联</span>
          <span slot="close">单选</span>
        </i-switch>
      </Row>
      <Row type="flex" justify="start" class="code-row-bg" style="margin:20px 0">
        <Col span="6">
          <Alert show-icon>
            当前选择编辑：
            <span class="select-title">{{editTitle}}</span>
            <a class="select-clear" v-if="form.id" @click="cancelEdit">取消选择</a>
          </Alert>
          <div class="tree-bar" :style="{maxHeight: maxHeight}">
            <Tree
              ref="tree"
              :data="data"
              :load-data="loadData"
              disableCheckbox
              @on-select-change="selectTree"
              :check-strictly="!strict"
            ></Tree>
          </div>
          <Spin size="large" fix v-if="loading"></Spin>
        </Col>
        <Col span="9" style="margin-left:10px">
          <Form ref="form" :model="form" :label-width="85" :rules="formValidate">
            <FormItem label="规格名称" prop="attrName" v-if="levelType === 1">
              <Input v-model="form.attrName"/>
            </FormItem>
            <FormItem label="规格名称" prop="attrValue" v-if="levelType === 2">
              <Input v-model="form.attrValue"/>
            </FormItem>
            <Form-item>
              <Button
                style="margin-right:5px"
                @click="submitEdit"
                :loading="submitLoading"
                type="primary"
                icon="ios-create-outline"
              >修改并保存</Button>
              <Button @click="handleReset">重置</Button>
            </Form-item>
          </Form>
        </Col>
      </Row>
    </Card>

    <Modal :title="modalTitle" v-model="modalVisible" :mask-closable="false" :width="500">
        <Form ref="formAdd" :model="formAdd" :label-width="85" :rules="formAddRules">
            <div v-if="showParent">
              <FormItem label="商品分类" prop="classId">
                <Poptip trigger="click" placement="right-start" title="选择商品分类" width="250">
                  <Input v-model="formAdd.className" readonly/>
                  <div slot="content" style="position:relative;min-height:5vh">
                    <Tree :data="dataEdit" :load-data="loadEditData" @on-select-change="selectTreeEdit($event, 2)" ref="trees"></Tree>

                    <!-- <Tree :data="dataEdit" :load-data="loadEditData" @on-select-change="selectTreeEdit($event,2)" ref="treeTwo"></Tree> -->
                    <Spin size="large" fix v-if="loadingEdit"></Spin>
                  </div>
                </Poptip>
              </FormItem>
            </div>
            <FormItem label="规格名称" prop="attrName" v-if="showParent">
              <Input v-model="formAdd.attrName"/>
            </FormItem>
            <FormItem label="规格名称" prop="attrValue" v-if="!showParent">
              <Input v-model="formAdd.attrValue"/>
            </FormItem>
            <!-- <FormItem label="购买状态" prop="buyState" v-if="!showParent">
              <Select v-model=""></Select>
            </FormItem>
            <FormItem label="规格名称" prop="attrValue" v-if="!showParent">
              <Input v-model="formAdd.attrValue"/>
            </FormItem> -->
        </Form>
        <div slot="footer">
            <Button type="text" @click="cancelAdd">取消</Button>
            <Button type="primary" :loading="submitLoading" @click="submitAdd">提交</Button>
        </div>
    </Modal>
  </div>
</template>

<script>
import {
  initDepartment,
  loadDepartment,
  addDepartment,
//   editDepartment,
  deleteDepartment,
  searchDepartment,
  getColorList
} from "@/api/index";
import uploadPicInput from "@/views/my-components/xboot/upload-pic-input";
export default {
  name: "classify-manage",
  components: {
      uploadPicInput
  },
  data() {
    return {
      modalType: 0,
      levelType: 1,
        loading: false,
        maxHeight: "500px",
        strict: true,
        userLoading: false,
        loadingEdit: false,
        modalVisible: false,
        showParent: false,
        modalTitle: "",
        editTitle: "",
        form: {
          id: "",
          attrId: "", // 规格id
          attrValue: "", // 规格属性名称
          classId: "", // 分类id
          className: "",
          attrName: "", // 规格名称
        },
        searchForm:{
          classId: "",
          className: ""
        },
        formAdd: {
          id: "",
          attrId: "", // 规格id
          attrValue: "", // 规格属性名称
          classId: "", // 分类id
          className: "",
          attrName: "", // 规格名称
        },
        formAddRules: {
          attrValue: [{ required: true, message: "名称不能为空", trigger: "blur" }],
          attrName: [{ required: true, message: "名称不能为空", trigger: "blur" }],
          classId: [{ required: true, message: "名称不能为空", trigger: "change" }],

        },
        formValidate: {
          title: [{ required: true, message: "名称不能为空", trigger: "blur" }]
        },
        submitLoading: false,
        data: [],
        dataEdit: [],
        users: []
    };
  },
  methods: {
    init() {
      this.getParentList();
      this.getParentListEdit();
    },
    clearAll () {
      this.searchForm.className = "";
      this.searchForm.classId = "";
      let data = this.$refs.trees.getSelectedNodes()[0];
      if (data) {
        data.selected = false;
      }
    },
    getParentList() {
      this.loading = true;
      this.postRequest("/itemAttrKey/getItemAttrKeyList", this.searchForm).then(res => {
        this.loading = false;
        if (res.success) {
          res.result.forEach(function(e) {
            if (e.isParent) {
              e.loading = false;
              // e.children = [];
            }
          });
          this.data = res.result;
        } else {
          this.$Message.warning(res.message)
          this.data = []
        }
      });
      // let data = this.$refs.treeOne.getSelectedNodes()[0];
      // if (data) {
      //   data.selected = false;
      // }
    },
    getParentListEdit() {
      this.loadingEdit = true;
      var param = {
        pid: ""
      }
      this.postRequest("/goodCategory/getGoodCategoryList", param).then(res=> {
        this.loadingEdit = false;
        if (res.success) {
          res.result.forEach(function(e) {
            if (e.isParent) {
              e.loading = false;
              e.children = [];
            }
          });
          this.dataEdit = res.result;
        }
      })
    },
    loadEditData (item, callback) {
      var data = {
        pid: item.id
      }
      this.postRequest("/goodCategory/getGoodCategoryList", data).then(res => {
        this.loadingEdit = false;
        if (res.success) {
          res.result.forEach(function(e) {
            if (e.isParent) {
              e.loading = false;
              e.children = [];
            }
          });
          callback(res.result);
        } else {
          this.$Message.warning(res.message)
        }
      });
    },
    loadData(item, callback) {
      console.log(item)
      item.children.forEach(function(e) {
        if (e.isParent) {
           e.loading = false;
           e.children= []
        }
      })
      callback(item.children)
    },

    selectTree(v) {
      console.log(v)
      this.modalType = 1;
      if (v.length > 0) {
        // 转换null为""
        for (let attr in v[0]) {
          if (v[0][attr] == null) {
            v[0][attr] = "";
          }
        }
        let str = JSON.stringify(v[0]);
        let data = JSON.parse(str);
        this.editTitle = data.title;
        // 回显
        this.form = data;
        this.form.id = data.id;
        
        if (data.isParent) {
          this.levelType = 1;
          this.formAdd.attrId = data.id;
          this.form.classId = data.classId;
          this.form.attrName = data.title;
          console.log(this.levelType)
        } else {
          this.levelType = 2;
          this.form.attrValue = data.title;
          console.log(this.levelType)
        }
      } else {
        this.cancelEdit();
      }
    },
    cancelEdit() {
      let data = this.$refs.tree.getSelectedNodes()[0];
      if (data) {
        data.selected = false;
      }
      this.$refs.form.resetFields();
      delete this.form.id;
      this.editTitle = "";
    },
    selectTreeEdit(v, k) {
      console.log(k)
      if (v.length > 0) {
        // 转换null为""
        for (let attr in v[0]) {
          if (v[0][attr] == null) {
            v[0][attr] = "";
          }
        }
        let str = JSON.stringify(v[0]);
        let data = JSON.parse(str);
        // this.form.id = data.id;
        // if (data.isParent) {
        //   this.$Message.warning("不能选择一级分类")
        // } else {
          if (k == 2) {
            this.formAdd.classId = data.id;
            this.formAdd.className = data.title;
          } else if (k === 1) {
            this.form.classId = data.id;
            this.form.className = data.title;
            this.$forceUpdate()
            console.log(this.form.className)
          } else if (k === 3) {
            this.searchForm.classId = data.id;
            this.searchForm.className = data.title;
          }
        // }
      }
    },
    cancelAdd() {
      this.modalVisible = false;
    },
    handleReset() {
      this.$refs.form.resetFields();
      this.form.type = 0;
    },
    submitEdit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!this.form.id) {
            this.$Message.warning("请先点击选择要修改的规格");
            return;
          }
          console.log(this.levelType)
          this.submitLoading = true;
          if (this.levelType === 1) {
            var data1 = {       
              id: this.form.id,
              classId: this.form.classId,
              attrName: this.form.attrName
            }
            this.postRequest("/itemAttrKey/insertOrderUpdateItemAttrKey", data1).then(res=> {
              this.submitLoading = false;
              if (res.success) {
                this.$refs.form.resetFields();
                this.$Message.success("操作成功");
                this.getParentList()
                this.modalVisible = false;
              } else {
                this.$Message.eroor(res.message);
                this.getParentList()
                this.modalVisible = false;
              }
            })
          } else {
            var data2 = {
              id: this.form.id,
              attrValue: this.form.attrValue
            }
            console.log(data2)
            this.postRequest("/itemAttrVal/insertOrderUpdateItemAttrVal", data2).then(res=> {
              this.submitLoading = false;
              if (res.success) {
                this.$refs.form.resetFields();
                this.$Message.success("操作成功");
                this.getParentList()
                this.modalVisible = false;
              } else {
                this.$Message.eroor(res.message);
                this.getParentList()
                this.modalVisible = false;
              }
            })
          }
        }
      });
    },
    // 添加
    submitAdd() {
      this.$refs.formAdd.validate(valid => {
        if (valid) {
          this.submitLoading = true;
          if (this.showParent) {//一级
          console.log('一级')
            // 添加
            var data1 = {       
              classId: this.formAdd.classId,
              attrName: this.formAdd.attrName
            }
            console.log(data1)
            this.postRequest("/itemAttrKey/insertOrderUpdateItemAttrKey", data1).then(res=> {
              this.submitLoading = false;
              if (res.success) {
                this.$refs.formAdd.resetFields();
                this.$Message.success("操作成功");
                this.getParentList()
                this.modalVisible = false;
              }
            })
          } else {// 二级
            console.log('二级')
            // 添加
            var data2 = {
              attrId: this.formAdd.attrId,
              attrValue: this.formAdd.attrValue
            }
            console.log(data2)
            this.postRequest("/itemAttrVal/insertOrderUpdateItemAttrVal", data2).then(res=> {
              this.submitLoading = false;
              if (res.success) {
                this.$refs.formAdd.resetFields();
                this.$Message.success("操作成功");
                this.getParentList()
                this.modalVisible = false;
              } else {
                this.$refs.formAdd.resetFields();
                this.$Message.success(res.message);
                this.modalVisible = false;
              }
              delete this.form.id;
              this.form.attrValue = "";
              this.$refs.form.resetFields();
              
              this.editTitle = "";
            })
          }
        }
      });
    },
    add() {
      if (this.form.id == "" || this.form.id == null) {
        this.$Message.warning("请先点击选择一个规格");
        return;
      }
      this.$refs.formAdd.resetFields();
      this.modalTitle = "添加子规格";
      this.showParent = false;
      this.modalType = 0;
      this.modalVisible = true;
    },
    addRoot() {
      this.modalTitle = "添加一级规格";
      // console.log(this.$refs.formAdd)
      let data = this.$refs.treeOne.getSelectedNodes()[0];
      if (data) {
        data.selected = false;
      }
      this.$refs.formAdd.resetFields();
      this.formAdd.className = "";
      this.formAdd.classId = ""
      this.showParent = true;
      this.modalType = 0;
      this.modalVisible = true;
    },
    delAll() {
      if (this.form.id =='') {
        this.$Message.warning("您还未勾选要删除的数据");
        return;
      }
      this.$Modal.confirm({
        title: "确认删除",
        content: "您确认要删除所选的数据?",
        onOk: () => {
          var data = {
            ids: this.form.id
          }
          if (this.levelType === 1) {
            this.postRequest("/itemAttrKey/removeItemAttrKey", data).then(res=> {
              if (res.success) {
                this.$Message.success("操作成功");
                this.getParentList();
                this.cancelEdit();
                this.$Modal.remove()
              } else {
                this.$Message.error(res.message);
                this.getParentList();
                this.cancelEdit();
                this.$Modal.remove()
              }
            })
          } else {
            this.postRequest("/itemAttrVal/removeItemAttrVal", data).then(res=> {
              if (res.success) {
                this.$Message.success("操作成功");
                this.getParentList();
                this.cancelEdit();
                this.$Modal.remove()
              } else {
                this.$Message.error(res.message);
                this.getParentList();
                this.cancelEdit();
                this.$Modal.remove()
              }
            })
          }
        }
      });
    }
  },
  mounted() {
    // 计算高度
    let height = document.documentElement.clientHeight;
    this.maxHeight = Number(height - 287) + "px";
    this.init();
  }
};
</script>